<template>
  <div class="container">
    <div class="top-nav">
      <el-descriptions title="点位配置详情" :column="2" border>
        <el-descriptions-item label="功能名称" label-class-name="my-label" content-class-name="my-content">{{ moduleInfo.functionName }}</el-descriptions-item>
        <el-descriptions-item label="模块名称">{{moduleInfo.moduleName}}</el-descriptions-item>
        <el-descriptions-item label="功能类型"><el-tag type="primary">{{moduleInfo.functionType}}</el-tag></el-descriptions-item>
        <el-descriptions-item label="模块英文名称">{{moduleInfo.moduleEngName}}</el-descriptions-item>
      </el-descriptions>
      <!--<el-form :inline="true" :model="moduleInfo" class="demo-form-inline">-->
      <!--  <el-form-item label="任务名称">-->
      <!--    <el-tag type="primary">{{moduleInfo.functionName}}</el-tag>-->
      <!--  </el-form-item>-->
      <!--  <el-form-item label="模块名称">-->
      <!--    <el-tag type="primary">{{moduleInfo.moduleName}}</el-tag>-->
      <!--  </el-form-item>-->
      <!--  <el-form-item label="缓存名称">-->
      <!--    <el-input v-model="formInline.user" placeholder="缓存名称"></el-input>-->
      <!--  </el-form-item>-->
      <!--  <el-form-item label="推送类型">-->
      <!--    <el-select v-model="formInline.region" placeholder="推送类型">-->
      <!--      <el-option label="Redis" value="shanghai"></el-option>-->
      <!--      <el-option label="MySQL" value="beijing"></el-option>-->
      <!--    </el-select>-->
      <!--  </el-form-item>-->
      <!--  <el-form-item label="推送地址"-->
      <!--                title="推送类型为RocketMQ、Kafka、MQTT时，推送地址为topic。推送类型为http时，推送地址为url">-->
      <!--    <el-input v-model="formInline.user" placeholder="推送地址"></el-input>-->
      <!--  </el-form-item>-->
      <!--  <el-form-item label="配置模板">-->
      <!--    <el-input v-model="formInline.user" placeholder="创建任务名称"></el-input>-->
      <!--  </el-form-item>-->
      <!--  <el-form-item label="配置模板">-->
      <!--    <el-button type="text">默认模板</el-button>-->
      <!--  </el-form-item>-->
      <!--  <el-form-item label="配置模板">-->
      <!--    <el-button type="text">默认模板</el-button>-->
      <!--  </el-form-item>-->
      <!--</el-form>-->
    </div>
    <div class="content">
      <div class="left-content">
        <div class="menu">
          <el-tag style="width: 100%;text-align: center"  type="primary" effect="dark">实例目录</el-tag>
        </div>
        <div class="menu">
          <el-input :placeholder="searchForm.type === '点位ID' ? '请输入点位ID' :'请输入点位名称'" v-model="searchForm.value" size="small">
              <el-select v-model="searchForm.type" slot="prepend" placeholder="请选择">
                <el-option
                    v-for="item in searchOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
              <el-button slot="append" icon="el-icon-search" size="small" @click="ready2GetDynamicAttrPage()"></el-button>
          </el-input>
        </div>
        <div class="menu">
          <el-tag style="user-select: none">实例路径</el-tag>
          <el-select v-model="value" :title="value" placeholder="请选择实例" ref="select" style="margin-left: 10px;width: 100%" size="small">
            <el-option
                style="height: auto; padding: 0"
                :value="value">
              <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick" @node-expand="handNodeExpand"></el-tree>
            </el-option>
          </el-select>
        </div>
        <div class="table">
          <el-table
              v-loading="instanceLoading"
              size="mini"
              ref="multipleTable"
              :data="leftPointPage.pointIdList"
              tooltip-effect="dark"
              highlight-selection-row
              height="100%"
              style="width: 100%"
              :row-key="(row)=>row.pointId"
              @select-all="handleLeftSelectAll"
              @select="handleLeftSelectPoint">
            <el-table-column
                type="selection"
                :reserve-selection="true"
                width="45">
            </el-table-column>
            <el-table-column
                prop="pointId"
                label="点位ID"
                width="80">
            </el-table-column>
            <el-table-column
                show-overflow-tooltip
                prop="pointName"
                label="点位名称">
            </el-table-column>
            <el-table-column
                width="70"
                prop="pointEngName"
                label="英文名称"
                show-overflow-tooltip>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <div>已选{{selectCount}}条</div>
          <div>
            <el-pagination
                background
                small
                hide-on-single-page
                layout="total, prev, pager, next"
                :current-page="leftPointPage.pageInfo.pageNum"
                :pager-count="5"
                :page-size="leftPointPage.pageInfo.pageSize"
                :total="leftPointPage.pageInfo.total"
                @current-change="readyGetDynamicAttrPage">
            </el-pagination>
          </div>
        </div>
      </div>
      <div class="right-content">
        <div class="tips">
          <i class="el-icon-warning-outline"/> 提示
          <p><small style="color: #74899a">左侧列表选中点位即可至右侧列表展示，右侧列表展示所有实例下已选中点位。最高支持添加1000个点位。</small></p>
        </div>
        <div class="right-menu">
          <el-button type="primary" size="mini" plain >全选</el-button>
          <el-button type="primary" size="mini" plain @click="clearModuleList">批量删除</el-button>
        </div>
        <div class="right-table">
          <el-table
              @selection-change="selectModuleListHandle"
              size="mini"
              ref="multipleTableRight"
              :data="moduleList"
              tooltip-effect="dark"
              height="100%"
              style="width: 100%">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column
                prop="pointId"
                label="点位ID">
            </el-table-column>
            <el-table-column
                prop="pointName"
                label="点位名称"
                width="300px"
                show-overflow-tooltip>
            </el-table-column>
            <el-table-column
                prop="pointEngName"
                label="英文名称"
                show-overflow-tooltip>
            </el-table-column>
            <el-table-column
                show-overflow-tooltip>
              <template #header>
                <el-tooltip content="用途：构建枚举类的枚举名称。命名规范：由英文、下划线、数字组成。模块内不得重复。" placement="top">
                  <span>自定义别名<i class="el-icon-question"></i></span>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <div v-if="!scope.row.isEditing">
                  <el-button type="text" v-if="scope.row.pointAlias===null" @click="startEdit(scope.row)">未设置</el-button>
                  <div v-else>
                    <el-button type="primary" size="mini" plain @click="startEdit(scope.row)">{{ scope.row.pointAlias}}</el-button>
                    <!--<el-button-->
                    <!--    type="text"-->
                    <!--    @click="startEdit(scope.row)">-->
                    <!--  <i class="el-icon-edit"></i>-->
                    <!--</el-button>-->
                  </div>


                </div>
                <div v-else>
                  <el-input
                      v-model="scope.row.pointAlias"
                      size="mini"
                      ref="aliasInput"
                      @blur="saveEdit(scope.row)"
                      @keyup.enter.native="saveEdit(scope.row)">
                  </el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                prop="dataType"
                label="数据类型"
                show-overflow-tooltip>
            </el-table-column>
            <el-table-column
                prop="instanceName"
                label="实例名称"
                show-overflow-tooltip>
            </el-table-column>

            <el-table-column
                show-overflow-tooltip
                prop="path"
                label="实例路径">
            </el-table-column>
            <el-table-column
                label="操作"
                width="80">
              <template slot-scope="scope">
                <el-button type="text" style="color: red" @click="deleteModuleItem(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <div>已选{{ selectModuleList.length }}条</div>
          <div style="color: #808183">共计{{moduleList.length}}条</div>
        </div>
      </div>
    </div>
    <div class="bottom">
      <el-button type="primary" plain size="mini" style="background-color: #eaecf1;color: #4a2f6d;border: none" @click="backPage()">取消
      </el-button>
      <el-button type="primary" size="mini" style="border: none" @click="submitModuleList">保存</el-button>
    </div>
  </div>
</template>

<script>
import background from "three/src/renderers/common/Background";
import {getTreeApi, getDynamicAttrPageApi, saveModulePointsApi} from "@/api/point";

export default {
  name: "",
  computed: {
    background() {
      return background
    }
  },
  data() {
    return {
      instanceLoading: false,
      value: '',
      select: '',
      selectCount: 0,
      searchOption: [
        { label: '点位ID', value: '点位ID' },
        { label: '点位名称', value: '点位名称' },
      ],
      searchForm: {
        type: '点位ID',
        value: '',
      },
      formInline: {
        user: '',
        region: ''
      },
      // 实例树形控件属性
      treeData: [{label: '全部分类', regionNodeId: 1, children: []}],
      defaultProps: {children: 'children', label: 'label'},
      // 左侧实例清单信息
      leftPointPage: {
        pageInfo: {
          pageNum: 1,
          pageSize: 20
        },
        pointIdList: []
      },
      instanceForm: {},
      // 右侧模块数据列表
      moduleList: [],
      selectModuleList:[],
      moduleInfo: {}
    }
  },
  created() {
    if (this.$route.query.item) {
      this.moduleInfo = JSON.parse(this.$route.query.item);
    }
  },
  mounted() {
    this.getTree(this.treeData[0]);
  },
  methods: {
    startEdit(row) {
      row.isEditing = true;
      this.$nextTick(() => {
        this.$refs.aliasInput.focus();
      });
    },
    saveEdit(row) {
      row.isEditing = false;
      // 此处可添加保存到服务器的逻辑
    },
    // 回退页面
    backPage() {
      this.$router.go(-1)
    },
    // 远程调用树形API，给树形控件封装数据
    getTree(data) {
      getTreeApi(data.regionNodeId).then(res=>{
        if (res.data != null) {
          // 说明还有目录,在当前data的children中添加
          const children = res.data.map(item=>{
            return {
              children: [],
              label: item.name,
              regionNodeId: item.id,
            }
          });
          this.$set(data, 'children', children);
          // 继续查看后续节点
          children.map(item=>{
            getTreeApi(item.regionNodeId).then(res=>{
              if (res.data != null) {
                // 说明还有目录,在当前data的children中添加
                const children = res.data.map(item => {
                  return {
                    children: [],
                    label: item.name,
                    regionNodeId: item.id,
                  }
                });
                this.$set(item, 'children', children);
              }
            })
          })
        }
      })
    },
    // 树形控件 - 点击节点
    handleNodeClick(data) {
      this.getTree(data);
      // 没有子节点说明当前是实例而非分类列表
      if (data.children.length === 0) {
        const path = this.findNodePath(this.treeData, data.label);
        this.value = path.join("/");
        // 手动关闭下拉框
        this.$refs.select.blur();
        // 清空上方的点位输入框
        this.searchForm.value = '';
        // 请求当前实例下的点位列表
        this.instanceForm.thingsId = data.regionNodeId;
        this.instanceForm.pageNum = 1;
        this.instanceForm.pageSize = 30;
        this.getDynamicAttrPage(this.instanceForm);
      }
    },
    getDynamicAttrPage(form) {
      this.instanceLoading = true;

      getDynamicAttrPageApi(form).then(res=>{
        if (res.data == null) {
          this.leftPointPage.pointIdList = null;
        }
        this.instanceLoading = false;
        this.leftPointPage.pointIdList = res.data.result.map(item => {
          return {
            pointId: item.attrId,
            pointName: item.name,
            pointEngName: item.engName,
            dataType: item.type,
            instanceName: item.thingsName,
            instanceEngName: item.thingsEngName,
            instanceId: item.thingsId,
            path: item.path,
            isEditing: false, // 编辑别名用，提前初始化
            customAlias: null
          }
        })
        this.leftPointPage.pageInfo = res.data.page;
        this.leftPointPage.pageInfo.total = Number(res.data.page.total)


      }).finally(()=>{this.instanceLoading = false})

    },
    // 切换左侧分页
    readyGetDynamicAttrPage(pageNum) {
      this.instanceForm.pageNum = pageNum;
      let form = this.instanceForm;
      if (this.searchForm.value !== null && this.searchForm.value !== '') {
        // 替换掉实例查询
        form.thingsId = null;
        if (this.searchForm.type === '点位ID') {
          form.attrId = this.searchForm.value;
        }else {
          form.name = this.searchForm.value;
        }
      }
      this.getDynamicAttrPage(form)
    },
    // 检索查询左侧分页信息
    ready2GetDynamicAttrPage() {
      if (this.searchForm.value == null || this.searchForm.value === '') {
        this.leftPointPage= {
          pageInfo: {
            pageNum: 1,
            pageSize: 20
          },
          pointIdList: []
        };
      }else {
        if (this.searchForm.type === '点位ID') {
          const form = {pageNum: 1, pageSize: 30, attrId: this.searchForm.value}
          this.getDynamicAttrPage(form);
        }else {
          const form = {pageNum: 1, pageSize: 30, name: this.searchForm.value}
          this.getDynamicAttrPage(form);
        }
        this.value = null;
      }
    },
    // 处理树形控件展开节点
    handNodeExpand(data) {
      this.getTree(data);
    },
    // 处理树形控件的路径名称
    findNodePath(tree, targetLabel, path = []) {
      for (const node of tree) {
        if (node.label === targetLabel) {
          return [...path, node.label];
        }
        if (node.children && node.children.length > 0) {
          const result = this.findNodePath(node.children, targetLabel, [...path, node.label]);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
    // 处理左侧选中的点位
    handleLeftSelectPoint(selection, row) {
      // 如果list为空，则新建一个list
      let list = this.moduleList;
      if (list) {
        // 遍历每一项selection, 如果list中没有则添加，有的不管
        if (selection.length > 0) {
          selection.forEach(item => {
            if (!list.some(listItem => listItem.pointId === item.pointId )) {
              list.push(item)
            }else {
              // list有当前selection参数中的项
              // 如果row不在selection中，说明是要剔除的,需要从list中剔除该项
              if (!selection.some(selectionItem => selectionItem.pointId === row.pointId)) {
                list = list.filter(listItem => listItem.pointId !== row.pointId)
              }
            }
          })
        }else {
          list = list.filter(listItem => listItem.pointId !== row.pointId);
        }
      }

      this.selectCount = list.length;
      // 将 list 的所有值放入 moduleList 中
      this.moduleList = list;

    },
    // 处理左侧全部选中或不选中
    handleLeftSelectAll(selection) {
      this.selectCount = selection.length;
      // 将 selection 的所有值放入 moduleList 中
      this.moduleList = selection;
    },


    // 处理右侧
    // 批量删除选中的模块数据
    clearModuleList() {
      this.$confirm('确认删除选中点位？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //js 将数组selectModuleList的所有对象从数组moduleList中删除
        // let list = this.moduleList;
        if (this.selectModuleList.length > 0) {
          this.moduleList = this.moduleList.filter(listItem => !this.selectModuleList.includes(listItem));
        }
        // this.moduleList = list;
        this.selectModuleList = [];

        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除模块中某一条记录
    deleteModuleItem(row){
      this.$confirm(`确认删除【${row.pointName}】点位`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.moduleList = this.moduleList.filter(item=>item !==row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    // 选中的模块
    selectModuleListHandle(selection) {
      this.selectModuleList = selection;

    },
    submitModuleList() {
      const id = this.moduleInfo.id;
      const form = {
        id: id,
        pointDetailList: this.moduleList
      }
      saveModulePointsApi(form).then(()=>{
        this.$message({
          message: '保存点位信息成功！',
          type: 'success'
        });
        this.$router.go(-1);
      }).catch(()=>{
        this.$message({
          message: '保存点位信息失败！',
          type: 'error'
        });
      })
    }
  },
}
</script>

<style scoped>
.container {
  width: 100vw;
  height: 100vh;

  .top-nav {
    height: 20%;
    background-color: #FFFFFF;
    padding: 10px 30px 0;
    margin: 0 20px;
  }

  .content {
    height: 70%;
    display: flex;
    margin: 0 50px;

    .left-content {
      width: 20%;
      background-color: #fafafa;
      border: 1px solid #e6e6e6;
      border-top-left-radius: 5px;
      border-bottom-left-radius: 5px;
      padding: 10px;
      .menu {
        display: flex;
        justify-content: left;
        margin-bottom: 10px;
       .btn {
         width: 60px;
         height: 32px;
       }
      }
      .table {
        height: 75%;
      }
      .pagination {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
        font-size: 14px;
      }
    }

    .right-content {
      width: 80%;
      background-color: #fafafa;
      border: 1px solid #e6e6e6;
      border-top-right-radius: 5px;
      border-bottom-right-radius: 5px;
      .tips {
        margin: 20px;
        padding: 20px;
        height: 100px;
        background-color: #f3f4f6;
        border-radius: 10px;
      }
      .right-menu {
        margin: 20px;
      }
      .right-table {
        margin: 20px 20px 0;
        height: 65%;
      }
      .pagination {
        margin: 5px 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 14px;
      }
    }
  }

  .bottom {
    height: 10%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}


/deep/ .input-with-select .el-input-group__prepend {
  background-color: #fff;
}
:deep(.el-select) {
  width: 130px;
}


</style>